﻿#ifndef NSSHARE_SYS_MESSAEG_LOOP_H_
#define NSSHARE_SYS_MESSAEG_LOOP_H_

#include <stdint.h>
#include "../base/base_object.h"

namespace nsshare
{
namespace sys
{

class MessageLoop : public base::BaseObject
{
public:
    static MessageLoop * Current();
private:
    static void SetCurrent(MessageLoop * loop);
public:
    class State
    {
        friend class MessageLoop;
    public:
        State();
        ~State();

        uint32_t deep() const;
        uint32_t idle_count() const;
    private:
        uint32_t depth_;
        uint32_t idle_count_;
    };
    class IdleWorker
    {
        friend class MessageLoop;
    protected:
        virtual uint32_t OnIdle(const State & state) = 0;
    };
public:
    MessageLoop();
    ~MessageLoop();
public:
    int Run();
    int Run(bool alertable);
    int Run(bool alertable, const bool & stop_signal);
    void Exit(int code);
    //build up stack pointer
    void ForceCreate();
    //make queue empty
    void Purge();

    void set_idle_worker(IdleWorker * worker);
private:
    bool Wait(uint32_t time_out, bool alertable);
    bool IsExitting(uint32_t & exit_code);
    void RunOnce();
    uint32_t InvokeIdleWorker();
private:
    State state_;
    IdleWorker * idle_worker_;
    void * dummy_handle_;
};

}
}

#endif